package controller;

import common.BaseServlet;
import service.GoodsDAO;
import service.GoodsImgDAO;
import service.ProductAttrDAO;
import service.ProductDAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;

import bean.Goods;
import bean.GoodsAllocation;
import bean.GoodsImg;
import bean.ProductAttr;
import bean.ProductValue;
import bean.TcImg;
import bean.ThirdCategory;

/**
 * Servlet implementation class ProductServlet
 */
@WebServlet("/Product")
public class ProductServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private static final GoodsDAO gdao=new GoodsDAO();
	private static final ProductDAO pdao=new ProductDAO();
	private static final GoodsImgDAO gImgdao=new GoodsImgDAO();
	private static final ProductAttrDAO padao=new ProductAttrDAO();
    /**
     * @see BaseServlet#BaseServlet()
     */
    public ProductServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void ajaxTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		//选择其他参数时
		PrintWriter out;
		out = response.getWriter();
		int attrid=Integer.parseInt(request.getParameter("attrid"));
		int attrValueid=Integer.parseInt(request.getParameter("attrValueid"));
		int tcid=Integer.parseInt(request.getParameter("tcid"));
		String attrName=request.getParameter("attrName");
		System.out.println("tcid:"+tcid);
		System.out.println("attrid:"+attrid);
		System.out.println("attrValueid:"+attrValueid);
		System.out.println("attrName:"+attrName);
		
		//获取已选择的数组型配置参数列表字符串
		String selectAttrListStr2=request.getParameter("selectAttrListStr2");
		System.out.println("selectAttrListStr2:"+selectAttrListStr2);
		//将数组型字符串转为对应配置参数对象的list集合
		int colorValueid;
        List<ProductValue> pvs=JSON.parseArray(selectAttrListStr2,ProductValue.class);
        for(Iterator<ProductValue> it=pvs.iterator();it.hasNext();) {
        	ProductValue pv=it.next();
        	if(pv.getAttrid()==attrid) {
        		System.out.println("将原来attrid："+attrid+"对应的attrValueid:"+pv.getAttrValueid()+"改为"+attrValueid);
        		pv.setAttrValueid(attrValueid);
        		String attrValueName=padao.queryByAttrValueid(attrValueid).get(0).getAttrValue();
        		pv.setAttrValue(attrValueName);
        	}
        }
        
        //根据改变的valueid获取该valueid拥有的所有其他配置参数
        List<GoodsAllocation> gaList=padao.queryALLOptionalValueByGoodsidsattrValueid(attrValueid, tcid);

        System.out.println("改变的参数对应商品所具有的其他所有参数");
        for(Iterator<GoodsAllocation> it=gaList.iterator();it.hasNext();) {
        	GoodsAllocation ga=it.next();
        	System.out.println("goodsid："+ga.getGoodsid()+",attrValueid:"+ga.getAttrValueid());
        }
        
        System.out.println("改变后的参数配置");
        //将改变后的参数配置在根据改变的valueid获取该valueid拥有的所有其他配置参数的集合中进行对比，看是否完全一致
        
        //改变后的参数配置可视为一个商品的配置valueid集合List<Integer>，将其与其他多个商品的配置valueid集合进行比较
        List<Integer> changeList=new ArrayList<Integer>();
        for(int i=0;i<pvs.size();i++) {
        	ProductValue pv=pvs.get(i);
        	changeList.add(pv.getAttrValueid());
        }
        //将改变后的参数拥有的其他配置存到map<Integer,List<Integer>>集合中
        Map<Integer,List<Integer>> gaMap=new HashMap<Integer,List<Integer>>();
        for(Iterator<GoodsAllocation> it=gaList.iterator();it.hasNext();) {
        	GoodsAllocation ga=it.next();
        	int tempGoodsid=ga.getGoodsid();
        	if(gaMap.containsKey(tempGoodsid)) {
        		gaMap.get(tempGoodsid).add(ga.getAttrValueid());
        	}
        	else {
        		gaMap.put(tempGoodsid, new ArrayList<Integer>());
        		gaMap.get(tempGoodsid).add(ga.getAttrValueid());
        	}
        }
        System.out.println("---------------------------------");
        boolean flag=false;
        int goodsid = 0;
        a:for(Entry<Integer, List<Integer>> entry:gaMap.entrySet()){
            List<Integer> list=entry.getValue();
            if(list.size()!=changeList.size()) {
            	continue a;
            }
            b:for(Integer i:list) {
            	if(!changeList.contains(i)) {
            		continue a;
            	}
            }
            goodsid=entry.getKey();
            flag=true;
        }
        System.out.println("---------------------------------");
        System.out.println(flag+":"+goodsid);
        //如果flag为false，说明改变后的配置参数并没有找到，
        //需要用改变的参数的默认配置的goodsid
        if(flag==false) {
        	for(Entry<Integer, List<Integer>> en : gaMap.entrySet()){
        		goodsid=en.getKey();
        		break;
		    }
        }
        //获取信息并存到字符串中传回去
        StringBuffer dataStr=new StringBuffer();
        dataStr.append("{");
        //根据tcid和goodsid获取商品详情表中的商品信息
  		Goods goods=pdao.queryByGoodsid(goodsid).get(0);
  		
  		//获取商品名字
  		String goodsName=goods.getName();
  		request.setAttribute("goodsName", goodsName);
  		//获取商品优惠信息
  		String discountMsg=goods.getDiscountMsg();
  		request.setAttribute("discountMsg", discountMsg);
  		//获取产品关键字
  		ThirdCategory tc=gdao.queryByTcid(tcid).get(0);
  		String keyword=tc.getKeyword();
  		request.setAttribute("keyword", keyword);
  		//获取原价格
  		double price=goods.getPrice();
  		request.setAttribute("price", price);
  		//获取优惠价格
  		double discountPrice=goods.getDiscountPrice();
  		request.setAttribute("discountPrice", discountPrice);
  		//获取运费
  		double postFee=goods.getPostFee();
  		request.setAttribute("postFee", postFee);
  		//获取库存数量
  		double count=goods.getCount();
  		request.setAttribute("count", count);
        
  		dataStr.append("\"goodsInfo\":{\"goodsid\":\""+goodsid+"\",\"goodsName\":\""+goodsName
  				+"\",\"discountMsg\":\""+discountMsg+"\",\"keyword\":\""+
  				keyword+"\",\"price\":\""+price+"\",\"discountPrice\":\""+
  				discountPrice+"\",\"postFee\":\""+postFee+"\",\"count\":\""+
  				count+"\"},");
  		
  		//根据goodsid获取选中商品的参数配置id，如1(红色)/3(64G)
		//[{\"attrid\":\"1\",\"attrValueid\":\"1\"},{\"attrid\":\"2\",\"attrValueid\":\"3\"}]
		List<ProductValue> selectAttrList=padao.queryByGoodsid(goodsid);
		StringBuffer selectAttrListStr=new StringBuffer();
		selectAttrListStr.append("[");
		for(Iterator<ProductValue> it=selectAttrList.iterator();it.hasNext();) {
			ProductValue pv=it.next();
			selectAttrListStr.append("{\"attrid\":\""+pv.getAttrid()+
					"\",\"attrValueid\":\""+pv.getAttrValueid()+
					"\",\"attrValue\":\""+pv.getAttrValue()+"\"},");
			
		}
		selectAttrListStr.deleteCharAt(selectAttrListStr.length()-1);
		selectAttrListStr.append("]");
		request.setAttribute("selectAttrListStr", selectAttrListStr);
  		
		dataStr.append("\"selectAttrList\":"+selectAttrListStr+",");
		
		//获取该颜色可选的配置参数
		int queryAttrValueid=padao.queryColoridByGoodsid(goodsid).get(0).getAttrValueid();
		List<GoodsAllocation> optionalAttrList=padao.queryOptionalValueByGoodsidsattrValueid(queryAttrValueid, tcid);
		StringBuffer optionalAttrListStr=new StringBuffer();
		optionalAttrListStr.append("[");
		for(Iterator<GoodsAllocation> it=optionalAttrList.iterator();it.hasNext();) {
			int optionalAttrValueid=it.next().getAttrValueid();
			optionalAttrListStr.append(optionalAttrValueid+",");
		}
		optionalAttrListStr.deleteCharAt(optionalAttrListStr.length()-1);
		optionalAttrListStr.append("]");
		request.setAttribute("optionalAttrListStr", optionalAttrListStr);
		
		dataStr.append("\"optionalAttrList\":"+optionalAttrListStr+",");
		
		//根据goodsid找到该商品的展示图片
		//["01.jpg","02.jpg"]	
		GoodsImg goodsImg=gImgdao.queryGoodsImg(goodsid).get(0);
		Map goodsImgMap;
		StringBuffer goodsImgStr=new StringBuffer();
		goodsImgStr.append("[");
		try {
			goodsImgMap=Tools.getStringProperties(goodsImg);
			Iterator<Map.Entry> it=goodsImgMap.entrySet().iterator();
			while(it.hasNext()) {
				Map.Entry en=it.next();
				String name=(String) en.getKey();
				//将属性的大写首字符变为原来的小写
				name = name.substring(0,1).toLowerCase()+name.substring(1);
				
				Object value=en.getValue();
				if(value==null) {
					continue;
				}
				if(value.getClass().getName().equals("java.lang.Integer")) {
					continue;
				}
				goodsImgStr.append("\""+value+"\",");
			}
			//去除最后一个字符","
			goodsImgStr.deleteCharAt(goodsImgStr.length()-1);
			
			goodsImgStr.append("]");
			request.setAttribute("goodsImgStr",new String(goodsImgStr));
			
			dataStr.append("\"goodsImgs\":"+goodsImgStr+"");
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
  		/*[
  		  goodsInfo:{name:xx,price:1200,discountmsg:xxxx,...},
  		  goodsImg:[img01,img02,img03,...],
  		  paList:[{id:1,name:颜色,value:[{name:幻影紫,id:1,imgsrc:img01.jpg},{name:幻影蓝,id:2,imgsrc:img02.jpg}]},{id:2,name:版本,value:[{name:6GB,id:3},{name:8GB,id:4}]}],
  		  selectAttrList:[{\"attrid\":\"1\",\"attrValueid\":\"1\"},{\"attrid\":\"2\",\"attrValueid\":\"3\"}],
  		  optionalAttrListStr:[3,4],
  		  ]*/
       
  		dataStr.append("}");
		out.print(dataStr);
		out.flush();
		
    }

	public String productInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out;
		out = response.getWriter();
		out.println("start");
		
		//获取请求中的tcid/scid/fcid/goodsid
		int tcid=Integer.parseInt(request.getParameter("tcid"));
		int scid=Integer.parseInt(request.getParameter("scid"));
		int fcid=Integer.parseInt(request.getParameter("fcid"));
		String goodsidStr=request.getParameter("goodsid");
		int goodsid;
		//如果goodsid为空，则默认查看数据库表中第一个对应tcid的商品
		if(goodsidStr==null) {
			Goods defaultGoods=pdao.queryByTcid(tcid).get(0);
			goodsid=defaultGoods.getGoodsid();
		}
		else{
			goodsid=Integer.parseInt(goodsidStr);
		}
		request.setAttribute("goodsid", goodsid);
		request.setAttribute("tcid", tcid);
		request.setAttribute("scid", scid);
		request.setAttribute("fcid", fcid);
		//在request中存入分类名称
		String fcName=gdao.queryByFcid(fcid).get(0).getName();
		request.setAttribute("fcName", fcName);
		String scName=gdao.queryByScid(scid).get(0).getName();
		request.setAttribute("scName", scName);
		//根据tcid和goodsid获取商品详情表中的商品信息
		Goods goods=pdao.queryByGoodsid(goodsid).get(0);
		
		//获取商品名字
		String goodsName=goods.getName();
		request.setAttribute("goodsName", goodsName);
		//获取商品优惠信息
		String discountMsg=goods.getDiscountMsg();
		request.setAttribute("discountMsg", discountMsg);
		//获取产品关键字
		ThirdCategory tc=gdao.queryByTcid(tcid).get(0);
		String keyword=tc.getKeyword();
		request.setAttribute("keyword", keyword);
		//获取原价格
		double price=goods.getPrice();
		request.setAttribute("price", price);
		//获取优惠价格
		double discountPrice=goods.getDiscountPrice();
		request.setAttribute("discountPrice", discountPrice);
		//获取运费
		double postFee=goods.getPostFee();
		request.setAttribute("postFee", postFee);
		//获取库存数量
		double count=goods.getCount();
		request.setAttribute("count", count);
		
		//根据goodsid获取选中商品的参数配置id，如1(红色)/3(64G)
		//[{\"attrid\":\"1\",\"attrValueid\":\"1\"},{\"attrid\":\"2\",\"attrValueid\":\"3\"}]
		List<ProductValue> selectAttrList=padao.queryByGoodsid(goodsid);
		StringBuffer selectAttrListStr=new StringBuffer();
		selectAttrListStr.append("[");
		for(Iterator<ProductValue> it=selectAttrList.iterator();it.hasNext();) {
			ProductValue pv=it.next();
			selectAttrListStr.append("{\"attrid\":\""+pv.getAttrid()+
					"\",\"attrValueid\":\""+pv.getAttrValueid()+
					"\",\"attrValue\":\""+pv.getAttrValue()+"\"},");
			
		}
		selectAttrListStr.deleteCharAt(selectAttrListStr.length()-1);
		selectAttrListStr.append("]");
		request.setAttribute("selectAttrListStr", selectAttrListStr);
		
		//根据goodsid找到商品该颜色所有的其他可用配置参数
		//[\"3\",\"4\"]
		//默认选中的attrValueid为颜色id
		
		int attrValueid=padao.queryColoridByGoodsid(goodsid).get(0).getAttrValueid();
		List<GoodsAllocation> optionalAttrList=padao.queryOptionalValueByGoodsidsattrValueid(attrValueid, tcid);
		StringBuffer optionalAttrListStr=new StringBuffer();
		optionalAttrListStr.append("[");
		for(Iterator<GoodsAllocation> it=optionalAttrList.iterator();it.hasNext();) {
			int optionalAttrValueid=it.next().getAttrValueid();
			optionalAttrListStr.append(optionalAttrValueid+",");
		}
		optionalAttrListStr.deleteCharAt(optionalAttrListStr.length()-1);
		optionalAttrListStr.append("]");
		request.setAttribute("optionalAttrListStr", optionalAttrListStr);
		
		//根据tcid获取该产品的所有可选择配置信息，如颜色/版本等
		/*"[{\"attrid\":\"1\",\"attrName\":\"颜色\",
		\"attrValues\":[{\"attrValueid\":\"1\",
		\"attrValueName\":\"蓝色\"},
		{\"attrValueid\":\"2\",\"attrValueName\":\"红色\"}]}]"*/
		List<ProductAttr> paList=padao.queryAllAttrByTcid(tcid);
		StringBuffer paListStr=new StringBuffer();
		paListStr.append("[");
		
		for(Iterator<ProductAttr> it=paList.iterator();it.hasNext();) {
			//根据配置id找到该产品拥有该项配置的所有选项，如：颜色:红色，蓝色
			ProductAttr pa=it.next();
			int attrid=pa.getAttrid();
			String attrName=padao.queryByAttrid(attrid).get(0).getAttrName();
			paListStr.append("{\"attrid\":\""+attrid+"\",\"attrName\":\""+attrName+"\",\"attrValues\":[");
			List<ProductValue> pvList=padao.queryAttrValueByTcidAndAttrid(tcid, attrid);
			for(Iterator<ProductValue> it2=pvList.iterator();it2.hasNext();) {
				ProductValue pv=it2.next();
				paListStr.append("{\"attrValueid\":\""+pv.getAttrValueid()
					+"\",\"attrValueName\":\""+pv.getAttrValue()+"\"");
				//如果该项配置是颜色，则根据attrValueid对应的商品把该商品对应颜色的图片存入参数中
				if(attrName.equals("颜色")) {
					String imgSrc=gImgdao.queryGoodsImgByAttrValueid(pv.getAttrValueid()).get(0).getImg01();
					paListStr.append(",\"imgSrc\":\""+imgSrc+"\"");
				}
				paListStr.append("},");
			}
			paListStr.deleteCharAt(paListStr.length()-1);
			paListStr.append("]},");
		}
		paListStr.deleteCharAt(paListStr.length()-1);
		paListStr.append("]");
		request.setAttribute("paListStr", paListStr);
		
		//根据goodsid找到该商品的展示图片
		//["01.jpg","02.jpg"]	
		GoodsImg goodsImg=gImgdao.queryGoodsImg(goodsid).get(0);
		Map goodsImgMap;
		StringBuffer goodsImgStr=new StringBuffer();
		goodsImgStr.append("[");
		try {
			goodsImgMap=Tools.getStringProperties(goodsImg);
			Iterator<Map.Entry> it=goodsImgMap.entrySet().iterator();
			while(it.hasNext()) {
				Map.Entry en=it.next();
				String name=(String) en.getKey();
				//将属性的大写首字符变为原来的小写
				name = name.substring(0,1).toLowerCase()+name.substring(1);
				
				Object value=en.getValue();
				if(value==null) {
					out.println(name+"没有属性值");
					continue;
				}
				if(value.getClass().getName().equals("java.lang.Integer")) {
					out.println("id不传入");
					continue;
				}
				goodsImgStr.append("\""+value+"\",");
				out.println(name+":"+value+"-"+value.getClass().getName());
			}
			//去除最后一个字符","
			goodsImgStr.deleteCharAt(goodsImgStr.length()-1);
			
			goodsImgStr.append("]");
			out.println("goodsImgStr"+goodsImgStr);
			request.setAttribute("goodsImgStr",new String(goodsImgStr));
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//根据tcid找到该id三级分类产品的详情图片
		//["01.jpg","02.jpg"]	
		TcImg tcImg=gdao.queryTcImg(tcid).get(0);
		out.println(tcImg.getImgid());
		out.println(tcImg.getDetailImg01());
		Map tcImgMap;
		StringBuffer tcImgStr=new StringBuffer();
		tcImgStr.append("[");
		try {
			//遍历获取tcImg的所有详情图片属性
			tcImgMap=Tools.getStringProperties(tcImg);
			Iterator<Map.Entry> it=tcImgMap.entrySet().iterator();
			while(it.hasNext()) {
				Map.Entry en=it.next();
				String name=(String) en.getKey();
				//将属性的大写首字符变为原来的小写
				name = name.substring(0,1).toLowerCase()+name.substring(1);
				
				Object value=en.getValue();
				if(value==null) {
					out.println(name+"没有属性值");
					continue;
				}
				if(value.getClass().getName().equals("java.lang.Integer")) {
					out.println("id不传入");
					continue;
				}
				if(name.equals("titleImg")) {
					out.println("titleImg不传入");
					continue;
				}
				tcImgStr.append("\""+value+"\",");
				out.println(name+":"+value+"-"+value.getClass().getName());
			}
			//去除最后一个字符","
			tcImgStr.deleteCharAt(tcImgStr.length()-1);
			
			tcImgStr.append("]");
			out.println("tcImgStr"+tcImgStr);
			request.setAttribute("tcImg",new String(tcImgStr));
				
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "f:jsp/Product";
		
	}

	@Override
	public String basefun(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return null;
	}

}
